<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="../include/tag.jsp" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <title>栏目管理</title>
    <link rel="stylesheet" href="${ctx}/css/common/list.css">
    <link rel="stylesheet" href="${ctx}/css/common/table.css">
    <link rel="stylesheet" href="${ctx}/css/ui/subject/subject_apply_list.css">
    <link rel="stylesheet" href="${ctx}/css/ui/form/jquery-ui.css">
    <%@include file="../include/commonFile.jsp" %>
    <style type="text/css">
        .sortable-placeholder {
            border: 2px dashed #dcdcdc;
            background: #f6f6f6
        }
    </style>
</head><body>
<!--头部-->
<%@include file="../include/header.jsp" %>
<div class="index-outside">
    <%@include file="../include/sidebar.jsp" %>
    <!--内容-->
    <section>
        <div class="section-main">

            <div style="padding-top: 20px;">
                <div class="content-left l" style="min-width: 230px;">
                    <h3>栏目管理</h3>
                    <ul class="apply-list" id="subject_apply_list">

                    </ul>
                    <div id="btn_list"></div>
                </div>
                <div class="content-right l">
                    <div class="f16 tc mt15" id="tip">可点击左侧“添加栏目”进行添加</div>
                    <div id="types" class="types" style="display: none;">
                        <p>
                            类型： <span id="typeName"></span>
                        </p>
                        <p>
                            说明：<span id="typeDesc"></span>
                        </p>
                    </div>
                    <div id="article_lists" style="display: none;">
                        <form class="layui-form" action="${ctx}/subject/apply/applyList.do" id="searchForm"
                              method="post">
                            <input type="hidden" name="pageNo" id="pageNo"/>
                            <input type="hidden" name="subjectId" value="${subject.id}"/>
                            <input type="hidden" name="applyId" class="applyId"/>
                            <!-- 							<div class="f-search-bar"> -->
                            <!-- 								<div class="search-container"> -->
                            <!-- 									<ul class="search-form-content"> -->
                            <!-- 										<li class="form-item-inline"><label class="search-form-lable">标题</label> -->
                            <!-- 											<div class="layui-input-inline"> -->
                            <!-- 												<input type="text" name="name" autocomplete="off" class="layui-input" placeholder="请输入查询标题"> -->
                            <!-- 											</div></li> -->
                            <!-- 										<li class="form-item-inline"> -->
                            <!-- 											<div class="sub-btns"> -->
                            <!-- 												<a class="layui-btn layui-btn-danger" id="submitBtn">确定</a> <a class="layui-btn layui-btn-normal" id="resetBtn">重置</a> -->
                            <!-- 											</div> -->
                            <!-- 										</li> -->
                            <!-- 										<li class="form-item-inline"></li> -->
                            <!-- 									</ul> -->
                            <!-- 								</div> -->
                            <!-- 							</div> -->
                        </form>
                        <div class="sub-btns tr">
                            <a class="layui-btn layui-btn-danger layui-btn-sm" id="articleBtn">
                                <i class="iconfont icon-add btn-icon"></i> 添加文章</a>
                        </div>
                        <div id="table_ctn" class="article-list"></div>
                        <div id="page_content" class="page-container"></div>
                    </div>
                    <div id="url_content" style="display: none;">
                        <form id="myForm" class="layui-form" method="post" action="${ctx}/subject/apply/save.do">
                            <div class="layui-form-item">
                                <label class="layui-form-label">链接：</label>
                                <div class="layui-input-block">
                                    <input type="text" class="layui-input" id="url" name="url" lay-verify="url" />
                                    <input type="hidden" name="id" class="applyId"/>
                                    <input type="hidden" name="subjectId" value="${subject.id}"/>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn layui-btn-danger" lay-submit lay-filter="*">保存生效</button>
                                    <button class="layui-btn layui-btn" type="button" id="resetBtn">取消</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="cl"></div>
            </div>
        </div><!--底部-->
        <%@include file="../include/footer.jsp" %>
    </section>
</div>

<script type="text/javascript" src="${ctx}/script/common/table_option.js"></script>
<script type="text/javascript" src="${ctx}/script/common/list.js"></script>
<script src="${ctx}/script/form/jquery-1.12.4.js"></script>
<script src="${ctx}/script/form/jquery-ui.js"></script>

<script type="text/html" id="article_template">
    <table class="layui-table">
        <colgroup>
            <col width="50%">
            <col width="60px">
            <col width="150px">
            <col>
        </colgroup>
        <thead>
        <tr>
            <th>标题</th>
            <th>链接</th>
            <th>更新时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        {{# var articles = d.articles; }}
        {{# var pageData = d.page; }}
        {{# if(articles.length > 0){ }}
        {{# layui.each(articles, function(index, item){ }}
        <tr data-id="{{ item.id }}">
            <td title="{{ item.title }}"><a class="ellipsis-1 db" href="${ctx}/article/article/articleDetail.do?id={{item.id}}&applyId={{ item.applyId }}">{{ item.title }}</a></td>
            <td>
                <a class="qr-btn" href="javascript:txz.openQrDialog({
					title:'扫码二维码可预览分享',
					detailList:[{
						title:'文章详情二维码',
						url:'{{item.qrCodeUrl }}',
						link:''
					}]
				})">查看</a>
            </td>
            <td>{{ util.getDateStr(item.updateDate).Format('yyyy-MM-dd hh:mm') }}</td>
            <td class="tb-opts">
                <div class="comm-opts">
                    {{# if(articles.length != 1){ }}
                    <a class="sort-handle" href="javascript:void(0);"><i class="iconfont icon-sort"></i> 拖曳</a>
                    {{# } }}
                    {{# var currIndex = (index + 1) + (pageData.page - 1) * pageData.limit; }}
                    {{# if(currIndex > 1){ }}
                    <a href="javascript:articleUpdateSort('up', '{{ item.id }}')"><i class="iconfont icon-top1"></i> 向上</a>
                    {{# } }}
                    {{# if(currIndex < pageData.totalCount){ }}
                    <a href="javascript:articleUpdateSort('down', '{{ item.id }}')"><i class="iconfont icon-down"></i> 向下</a>
                    {{# } }}

                    <a href="${ctx}/article/article/articleForm.do?id={{ item.id }}&subjectId=${subject.id}&applyId={{ item.applyId }}"><i
                            class="iconfont icon-edit btn-icon"></i> 编辑</a>

                    <a href="javascript:txz.deleteObject('确定要删除吗？', '${ctx}/article/article/delete.do?id={{ item.id }}&subjectId=${subject.id}&applyId={{ item.applyId }}')"><i
                            class="iconfont icon-delete btn-icon"></i> 删除</a>
                </div>
            </td>
        </tr>
        {{# }); }}
        {{# }else{ }}
        <tr><td colspan="4" align="center">该栏目还没有文章</td></tr>
        {{# } }}
        </tbody>
    </table>
</script>
<script type="text/html" id="apply_template">
    {{# var applyId = d.firstId }}
    {{#  layui.each(d.applies, function(index, item){ }}
    <li data-id="{{ item.id }}" class="apply-item {{ item.id == applyId ? 'activie' : '' }} {{ item.id }}"
        onclick="javascript:loadData('{{ item.id }}');">
        <div style="flex : 1;">
            <a title="{{ item.name }}" style="width:160px;" class="{{ item.id }} ellipsis-1 db" href="javascript:void(0);">{{item.name }}</a>
        </div>
        <div class="opts-btn" style="display: none; float: right">
            {{# if(d.applies.length != 1){ }}
            <a class="sort-handle" href="javascript:void(0);"><i class="iconfont icon-sort btn-icon"></i></a>
            {{# } }}
            <a href="${ctx}/subject/apply/applyForm.do?id={{ item.id }}&subjectId=${subject.id}"><i
                    class="iconfont icon-edit btn-icon"></i> </a>
            <a href="javascript:txz.deleteObject('确定要删除吗？', '${ctx}/subject/apply/delete.do?applyId={{ item.id }}&subjectId=${subject.id}')"><i
                    class="iconfont icon-delete btn-icon"></i> </a>
        </div>
    </li>
    {{# }); }}
</script>
<script type="text/html" id="btn_template">
    <div>
        <a href="${ctx}/subject/apply/applyForm.do?subjectId=${subject.id}"
           class="layui-btn layui-btn-radius layui-btn-danger layui-btn-xs">
            <i class="iconfont icon-add btn-icon"></i> 添加栏目
        </a>
        <%--{{# if(d.length > 1){ }}
        <a href="javascript:void(0);" class="layui-btn layui-btn-radius layui-btn-danger layui-btn-xs" onclick="updateSort('up')">
            <i class="iconfont icon-top1 btn-icon"></i> 向上
        </a>
        <a href="javascript:void(0);" class="layui-btn layui-btn-radius layui-btn-danger layui-btn-xs" onclick="updateSort('down')">
            <i class="iconfont icon-down btn-icon"></i> 向下
        </a>
        {{# } }}--%>
    </div>
</script>
<script type="text/javascript">

    var laytpl = null;
    var laypage = null;
    var pageData = null;
    var data_applyId = '${firstId}'; // 栏目id

    $(function () {
        layui.use(['laypage', 'laytpl', 'form'], function () {
            laytpl = layui.laytpl;
            laypage = layui.laypage;
            var form = layui.form;

            form.verify({
                url: function (value) {
                    if (value == "") {
                        return "请填写链接";
                    } else if (!util.checkLink(value)) {
                        return "链接格式错误";
                    }
                }
            });

            //监听提交
            form.on('submit', function (data) {
                txz.submitObject(data.elem, function (callBack) {
                    var action = $("#myForm").attr("action");
                    $.post(action, $('#myForm').serialize(), function (res) {
                        typeof callBack === 'function' && callBack();
                        if (res.success) {
                            util.layerMsgSuccess('保存成功', function () {
                                location.href = "${ctx}/subject/apply/applyList.do?subjectId=" + res.data.subjectId + "&applyId=" + res.data.applyId;
                            });
                        } else {
                            util.layerMsgError('保存失败');
                        }
                    });
                })
                return false;
            });

            loadApplyList('${subject.id}', '', function () {
                if (util.isValid(data_applyId)) {
                    loadData(data_applyId);
                }
            });

            // 文章拖拽排序
            $(".article-list").sortable({
                items: "tr",
                handle: ".sort-handle",
                placeholder: 'sortable-placeholder',
                opacity: 0.5,
                forcePlaceholderSize: true,
                stop: function (event, ui) {
                    //loading层
                    var loadIndex = layer.load(1, {
                        shade: [0.1,'#fff'] //0.1透明度的白色背景
                    });
                    var result = {};
                    $("tbody tr").each(function (index, ele) {
                        var articleId = $(ele).data("id");
                        result[articleId] = (index + 1) + (pageData.page - 1) * pageData.limit;
                    });
                    var jsonStr = JSON.stringify(result);
                    $.post("${ctx}/article/article/dragUpdateSort.do", {
                        jsonStr : jsonStr
                    }, function (res) {
                        layer.close(loadIndex);
                        if (res.success) {

                        } else {
                            if (util.isValid(res.description)) {
                                util.layerMsgError(res.description);
                            } else {
                                util.layerMsgError("更新排序异常");
                            }
                        }
                    });
                }
            });
            $(".article-list").disableSelection();

            // 栏目拖拽排序
            $(".apply-list").sortable({
                items: "li",
                handle: ".sort-handle",
                placeholder: 'sortable-placeholder',
                opacity: 0.5,
                forcePlaceholderSize: true,
                stop: function (event, ui) {
                    //loading层
                    var loadIndex = layer.load(1, {
                        shade: [0.1,'#fff'] //0.1透明度的白色背景
                    });
                    var result = {};
                    $(".apply-list .apply-item").each(function (index, ele) {
                        var articleId = $(ele).data("id");
                        result[articleId] = (index + 1) + (pageData.page - 1) * pageData.limit;
                    });
                    var jsonStr = JSON.stringify(result);
                    $.post("${ctx}/subject/apply/dragUpdateSort.do", {
                        jsonStr : jsonStr
                    }, function (res) {
                        layer.close(loadIndex);
                        if (res.success) {

                        } else {
                            if (util.isValid(res.description)) {
                                util.layerMsgError(res.description);
                            } else {
                                util.layerMsgError("更新排序异常");
                            }
                        }
                    });
                }
            });
            $(".apply-list").disableSelection();
        });
        $("#resetBtn").click(function () {
            $("#myForm").find("input[type=text]").val("");
        });

        $('tbody').delegate('td', 'click', function (e) {
            var $target = $(e.target);

            if ($target.hasClass('qr-btn')) {
                var dialog = $target.closest("tr").find(".f-def-dialog");
                $(dialog).fadeIn();
            }
        });
        $('tbody').delegate('.f-def-dialog .close-icon', 'click', function (e) {
            $(this).closest('.f-def-dialog').fadeOut();
        });

        $("#subject_apply_list").delegate('li,div,a', 'mouseover mouseout', function (e) {
            var $target = $(e.target);
            if (e.type == "mouseover") {
                $(this).find("a").addClass("red");
                $(this).find(".opts-btn").show();
            } else if (e.type == "mouseout") {
                $(this).find("a").removeClass("red");
                $(this).find(".opts-btn").hide();
            }
        });
    });

    function loadPage(page) {
        loadPageNew({
            elem: 'page_content',
            totalCount: page.totalCount,
            page: page.page,
            limit: page.limit,
            formName: 'searchForm',
            callback: function () {
                $.post("${ctx}/subject/apply/loadJsonData.do", $('#searchForm').serialize(), function(data) {
                    // 填充数据
                    appendHtml(data);
                    pageData = data.page;
                });
            }
        });
    }

    // 加载文章列表
    function appendHtml(data) {
        var content = $("#table_ctn");
        $(content).html("");
        var getTpl = $("#article_template").html();
        laytpl(getTpl).render(data, function (html) {
            content.append(html);
        });
    }

    function appendBtn(applies) {
        var content = $("#btn_list");
        $(content).html("");
        var getTpl = $("#btn_template").html();
        laytpl(getTpl).render(applies, function (html) {
            content.append(html);
        });
    }

    // 加载栏目列表
    function loadApplyList(subjectId, applyId, callback) {
        $.post("${ctx}/subject/apply/getApplyList.do", {"subjectId": subjectId, "applyId": applyId}, function (res) {
            var content = $("#subject_apply_list");
            content.html("");
            var getTpl = $("#apply_template").html();
            laytpl(getTpl).render(res.data, function (html) {
                content.append(html);
            });

            data_applyId = res.data.firstId;

            if (util.isValid(data_applyId)) {
                $("#tip").hide();
            } else {
                $("#tip").show();
            }

            appendBtn(res.data.applies);
            typeof callback === 'function' && callback();
        })
    }

    function loadData(applyId, pageNo) {
        data_applyId = applyId;
        $("#subject_apply_list").find("li").removeClass("activie");
        $("#subject_apply_list").find("li[class*=" + applyId + "]").addClass("activie");
		$.post("${ctx}/subject/apply/loadJsonData.do", {
			applyId : applyId,
			pageNo : 1,
			title : ""
		}, function(data) {
			$("#types").show();
			var typename = "";
			var typedesc = "";
			if (data.subjectApply.type == "url") {
				typename = "单链接";
				typedesc = "可以连接到一个固定的网页链接地址";
				$("#url_content").show();
				$("#article_lists").hide();
				$("#url").val(data.subjectApply.url);
			} else if (data.subjectApply.type == "article") {
				typename = "单篇文章";
				typedesc = "可以指向一篇文章内容";
				$("#url_content").hide();
				$("#article_lists").show();

				if (data.articles.length == 1) {
					$("#articleBtn").parent().hide();
				} else if (data.articles.length == 0) {
                    $("#articleBtn").parent().show();
                }
			} else if (data.subjectApply.type == "channel") {
				typename = "文章列表";
				typedesc = "可以添加多个文章内容";
				$("#url_content").hide();
				$("#article_lists").show();
				$("#articleBtn").parent().show();
			}
			$("#articleBtn").attr("href",'${ctx}/article/article/articleForm.do?applyId=' + data.subjectApply.id);

			$(".applyId").val(data.subjectApply.id);

			$("#typeName").text(typename);
			$("#typeDesc").text(typedesc);

            // 加载分页
            loadPage(data.page);
            pageData = data.page;

            // 填充数据
            appendHtml(data);

            tbOption.init();
        });
    }

    // 向上/向下
    function updateSort(type) {
        //loading层
        var loadIndex = layer.load(1, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });
        $.post("${ctx}/subject/apply/updateSort.do", {"applyId": data_applyId, "type": type}, function (res) {
            layer.close(loadIndex);
            setTimeout(function () {
                if (res.success == true) {
                    loadApplyList("${subject.id}", data_applyId);
                } else {
                    util.layerAlertError(res.description)
                }
            }, 500);
        });
    }

    /**
     * 商品向上向下排序
     * @param op 操作
     */
    function articleUpdateSort(op, articleId) {
        //loading层
        var loadIndex = layer.load(1, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });
        $.post("${ctx}/article/article/upDownUpdateSort.do", {
            articleId : articleId,
            type : op,
            applyId : data_applyId
        }, function (res) {
            layer.close(loadIndex);
            if (res.success) {
                loadData(data_applyId, pageData.page);
            } else {
                if (util.isValid(res.description)) {
                    util.layerMsgError(res.description);
                } else {
                    util.layerMsgError("更新排序异常");
                }
            }
        })

    }
</script>
<script type="text/javascript">
    txz.initHeader({
        nav:[{
            name: '手机官网管理',
            href: '${ctx}/subject/subject/subjectList.do'
        },{
            name: '${subject.name}',
            curr: true
        }],
        btns:[{
            name: '返回',
            href: '${ctx}/subject/subject/subjectList.do',
            icon: 'back'
        }]
    });
</script>
</body>
</html>